import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Paper,
  Button,
  IconButton,
  Stack,
  TextField,
  Alert,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Switch,
  FormControlLabel
} from '@mui/material';
import { ArrowBack as ArrowBackIcon } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { 
  isPermissionGranted,
  requestPermission,
  sendNotification,
  createChannel,
  Importance,
  Visibility
} from '@tauri-apps/plugin-notification';

const NotificationCasePage = () => {
  const navigate = useNavigate();
  const [permissionGranted, setPermissionGranted] = useState(false);
  const [title, setTitle] = useState('Tauri 通知');
  const [body, setBody] = useState('这是一条来自 Tauri 的测试通知！');
  const [importance, setImportance] = useState('Default');
  const [useChannel, setUseChannel] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    checkPermission();
  }, []);

  const checkPermission = async () => {
    try {
      const granted = await isPermissionGranted();
      setPermissionGranted(granted);
      if (!granted) {
        const permission = await requestPermission();
        setPermissionGranted(permission === 'granted');
      }
    } catch (err) {
      setError('检查通知权限时出错：' + err.toString());
    }
  };

  const createNotificationChannel = async () => {
    try {
      await createChannel({
        id: 'tauri-demo',
        name: 'Tauri 示例',
        description: 'Tauri 示例通知频道',
        importance: Importance[importance],
        visibility: Visibility.Private,
        lights: true,
        lightColor: '#2196f3',
        vibration: true
      });
      return true;
    } catch (err) {
      setError('创建通知频道时出错：' + err.toString());
      return false;
    }
  };

  const handleSendNotification = async () => {
    try {
      setError(null);
      
      if (!permissionGranted) {
        await checkPermission();
        if (!permissionGranted) {
          setError('未获得通知权限');
          return;
        }
      }

      const notificationOptions = {
        title,
        body
      };

      if (useChannel) {
        const channelCreated = await createNotificationChannel();
        if (channelCreated) {
          notificationOptions.channelId = 'tauri-demo';
        }
      }

      await sendNotification(notificationOptions);
    } catch (err) {
      setError('发送通知时出错：' + err.toString());
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      <Stack direction="row" alignItems="center" spacing={2} sx={{ mb: 3 }}>
        <IconButton 
          onClick={() => navigate('/')}
          sx={{ color: 'text.primary' }}
        >
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h4" component="h1" sx={{ userSelect: 'none' }}>
          通知示例
        </Typography>
      </Stack>

      <Paper sx={{ p: 3, mb: 3 }}>
        <Typography variant="body1" paragraph>
          本示例展示如何使用 Tauri Notification Plugin 发送系统通知。
          {permissionGranted ? 
            '✅ 已获得通知权限' : 
            '❌ 未获得通知权限，请点击发送通知按钮授权'
          }
        </Typography>

        <Stack spacing={3}>
          <TextField
            fullWidth
            label="通知标题"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />

          <TextField
            fullWidth
            label="通知内容"
            value={body}
            onChange={(e) => setBody(e.target.value)}
            multiline
            rows={2}
          />

          <FormControl fullWidth>
            <InputLabel>重要程度</InputLabel>
            <Select
              value={importance}
              label="重要程度"
              onChange={(e) => setImportance(e.target.value)}
            >
              <MenuItem value="None">无</MenuItem>
              <MenuItem value="Min">最低</MenuItem>
              <MenuItem value="Low">低</MenuItem>
              <MenuItem value="Default">默认</MenuItem>
              <MenuItem value="High">高</MenuItem>
            </Select>
          </FormControl>

          <FormControlLabel
            control={
              <Switch
                checked={useChannel}
                onChange={(e) => setUseChannel(e.target.checked)}
              />
            }
            label="使用通知频道（Android）"
          />

          <Button 
            variant="contained" 
            onClick={handleSendNotification}
            size="large"
          >
            发送通知
          </Button>

          {error && (
            <Alert severity="error">
              {error}
            </Alert>
          )}
        </Stack>
      </Paper>
    </Box>
  );
};

export default NotificationCasePage; 